package com.wzz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzz.entity.ExamQuestion;
import com.wzz.entity.ExamRecord;
import com.wzz.entity.Question;
import com.wzz.entity.QuestionBank;
import com.wzz.mapper.DataMapper;
import com.wzz.service.ExamQuestionService;
import com.wzz.service.QuestionBankService;
import com.wzz.service.QuestionService;
import com.wzz.service.impl.ExamRecordServiceImpl;
import com.wzz.utils.OSSUtil;
import com.wzz.vo.CommonResult;
import com.wzz.vo.PageResponse;
import com.wzz.vo.QuestionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by liutao
 * @implNote 11/7 19:44
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "学生权限相关的接口")
@RequestMapping(value = "/student")
public class StudentController {

    private final OSSUtil ossUtil;

    private final ExamRecordServiceImpl examRecordService;

    private final QuestionService questionService;

    private final ExamQuestionService examQuestionService;

    @GetMapping("/getMyGrade")
    @ApiOperation("获取个人成绩(分页 根据考试名查询)")
    @ApiImplicitParams({@ApiImplicitParam(name = "username", value = "系统唯一用户名", required = true, dataType = "string", paramType = "query"), @ApiImplicitParam(name = "pageNo", value = "当前页面数", required = true, dataType = "int", paramType = "query"), @ApiImplicitParam(name = "pageSize", value = "当前页面大小", required = true, dataType = "int", paramType = "query"), @ApiImplicitParam(name = "examId", value = "考试唯一id", dataType = "int", paramType = "query")})
    public CommonResult<PageResponse<ExamRecord>> getMyGrade(String username, Integer pageNo, Integer pageSize, @RequestParam(required = false) Integer examId) {
        return CommonResult.<PageResponse<ExamRecord>>builder().data(examRecordService.getUserGrade(username, examId, pageNo, pageSize)).build();
    }

    @GetMapping("/getCertificate")
    @ApiOperation("生成证书接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "examName", value = "考试名称", required = true, dataType = "string", paramType = "query"), @ApiImplicitParam(name = "examRecordId", value = "考试记录id", required = true, dataType = "int", paramType = "query")})
    public void getCertificate(HttpServletResponse response, @RequestParam(name = "examName") String examName, @RequestParam(name = "examRecordId") Integer examRecordId) throws UnsupportedEncodingException {
        examRecordService.createExamCertificate(response, URLDecoder.decode(examName, "UTF-8"), examRecordId);
    }

    @PostMapping("/addExamRecord")
    @ApiOperation("保存考试记录信息,返回保存记录的id")
    @ApiImplicitParams({@ApiImplicitParam(name = "examRecord", value = "考试记录实体对象", required = true, dataType = "examRecord", paramType = "body")})
    public CommonResult<Integer> addExamRecord(@RequestBody ExamRecord examRecord, HttpServletRequest request) {
        return CommonResult.<Integer>builder().data(examRecordService.addExamRecord(examRecord, request)).build();
    }

    @GetMapping("/getQuestionById/{id}")
    @ApiOperation("根据id获取题目信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "问题id", required = true, dataType = "int", paramType = "path")
    })
    public CommonResult<QuestionVo> getQuestionById(@PathVariable("id") Integer id) {
        return CommonResult.<QuestionVo>builder()
                .data(questionService.getQuestionVoById(id))
                .build();
    }

    @GetMapping("/getQuestionByIds")
    @ApiOperation("根据id集合获取题目信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "问题id集合", required = true, dataType = "int", paramType = "params")
    })
    public CommonResult<PageResponse<QuestionVo>> getQuestionById(@RequestParam("ids") List<Integer> ids) {
        return CommonResult.<PageResponse<QuestionVo>>builder()
                .data(questionService.getQuestionVoByIds(ids))
                .build();
    }

    @GetMapping("/getExamRecordById/{recordId}")
    @ApiOperation("根据考试的记录id查询用户考试的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordId", value = "考试记录id", required = true, dataType = "int", paramType = "query")
    })
    public CommonResult<ExamRecord> getExamRecordById(@PathVariable Integer recordId) {
        return CommonResult.<ExamRecord>builder()
                .data(examRecordService.getExamRecordById(recordId))
                .build();
    }

    @GetMapping("/getExamQuestionByExamId/{examId}")
    @ApiOperation("根据考试id查询考试中的每一道题目id和分值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", required = true, dataType = "int", paramType = "query")
    })
    public CommonResult<ExamQuestion> getExamQuestionByExamId(@PathVariable Integer examId) {
        return CommonResult.<ExamQuestion>builder()
                .data(examQuestionService.getExamQuestionByExamId(examId))
                .build();
    }

    @PostMapping("/uploadQuestionImage")
    @ApiOperation("接受前端上传的图片,返回上传图片地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "file", paramType = "body")
    })
    public CommonResult<String> uploadQuestionImage(MultipartFile file) throws Exception {
        log.info("开始上传文件: {}", file.getOriginalFilename());
        return CommonResult.<String>builder()
                .data(ossUtil.picOSS(file))
                .message("上传成功")
                .build();
    }
    @Autowired
    private DataMapper dataMapper;

    private final QuestionBankService questionBankService;

    @GetMapping("/huaxiang")
    @ApiOperation("获取个人用户画像")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "系统唯一", required = true, dataType = "string", paramType = "query")})
    public CommonResult<List> huaxiang(Integer userId) {
        List<QuestionBank> list = questionBankService.list(new LambdaQueryWrapper<>());
        List<Map<String, Object>> mapList = new ArrayList<>();

        // 获取用户做对的题目ID
        String tidsql = "SELECT GROUP_CONCAT( tqid ) tqid FROM exam_record WHERE user_id = "+userId+" GROUP BY user_id";
        List<Map<String,Object>> tddataList = dataMapper.ssql(tidsql);
        
        // 获取用户做的所有考试记录
        String recordSql = "SELECT * FROM exam_record WHERE user_id = " + userId;
        List<Map<String,Object>> recordList = dataMapper.ssql(recordSql);
        
        Map<Integer, Double> weightedScoreMap = new HashMap<>();
        
        if(recordList.size() > 0) {
            for(Map<String, Object> record : recordList) {
                // 获取做对的题目ID
                String correctQuestionIds = record.get("tqid") != null ? record.get("tqid").toString() : "";
                if(!StringUtils.isEmpty(correctQuestionIds)) {
                    String[] correctIds = correctQuestionIds.split(",");
                    
                    // 获取考试中的所有题目ID
                    String questionIds = record.get("question_ids").toString();
                    String[] allIds = questionIds.split(",");
                    
                    // 获取考试ID
                    Integer examId = Integer.parseInt(record.get("exam_id").toString());
                    
                    // 获取该考试的题目分数
                    String scoresSql = "SELECT scores FROM exam_question WHERE exam_id = " + examId;
                    List<Map<String,Object>> scoresData = dataMapper.ssql(scoresSql);
                    String[] scores = new String[0];
                    if(scoresData.size() > 0 && scoresData.get(0).get("scores") != null) {
                        scores = scoresData.get(0).get("scores").toString().split(",");
                    }
                    
                    // 处理每道题目
                    for(int i = 0; i < allIds.length; i++) {
                        String qid = allIds[i];
                        Question question = questionService.getById(qid);
                        
                        if(question != null) {
                            // 获取题目权重
                            String weights = question.getWeight();
                            String[] bankIds = question.getQuBankId().split(",");
                            String[] weightValues = weights != null ? weights.split(",") : new String[bankIds.length];
                            
                            // 如果没有设置权重，默认为1
                            if(weights == null || weights.isEmpty()) {
                                for(int w = 0; w < weightValues.length; w++) {
                                    weightValues[w] = "1";
                                }
                            }
                            
                            // 获取题目分数
                            double score = 0;
                            if(i < scores.length) {
                                score = Double.parseDouble(scores[i]);
                            }
                            
                            // 判断是否做对了此题
                            boolean isCorrect = false;
                            for(String correctId : correctIds) {
                                if(correctId.equals(qid)) {
                                    isCorrect = true;
                                    break;
                                }
                            }
                            
                            // 根据是否做对计算分数
                            double questionScore = isCorrect ? score : 0;
                            
                            // 根据权重分配分数到各分类
                            for(int j = 0; j < bankIds.length; j++) {
                                Integer bankId = Integer.parseInt(bankIds[j]);
                                double weight = j < weightValues.length ? Double.parseDouble(weightValues[j]) : 1.0;
                                double weightedScore = questionScore * weight;
                                
                                weightedScoreMap.put(bankId, weightedScoreMap.getOrDefault(bankId, 0.0) + weightedScore);
                            }
                        }
                    }
                }
            }
        }
        
        // 构建返回结果
        for (QuestionBank questionBank : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", questionBank.getBankName());
            double value = weightedScoreMap.getOrDefault(questionBank.getBankId(), 0.0);
            map.put("value", value);
            mapList.add(map);
        }
        
        return CommonResult.<List>builder()
                .data(mapList)
                .build();
    }
    @GetMapping("/huaxiangAlls")
    @ApiOperation("获取整体用户画像")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "系统唯一", required = true, dataType = "string", paramType = "query")})
    public CommonResult<List> huaxiangAlls(Integer userId) {
        List<QuestionBank> list = questionBankService.list(new LambdaQueryWrapper<>());
        List<Map<String, Object>> mapList = new ArrayList<>();

        // 获取所有考试记录
        String recordSql = "SELECT * FROM exam_record";
        List<Map<String,Object>> recordList = dataMapper.ssql(recordSql);
        
        Map<Integer, Double> weightedScoreMap = new HashMap<>();
        
        if(recordList.size() > 0) {
            for(Map<String, Object> record : recordList) {
                // 获取做对的题目ID
                String correctQuestionIds = record.get("tqid") != null ? record.get("tqid").toString() : "";
                if(!StringUtils.isEmpty(correctQuestionIds)) {
                    String[] correctIds = correctQuestionIds.split(",");
                    
                    // 获取考试中的所有题目ID
                    String questionIds = record.get("question_ids").toString();
                    String[] allIds = questionIds.split(",");
                    
                    // 获取考试ID
                    Integer examId = Integer.parseInt(record.get("exam_id").toString());
                    
                    // 获取该考试的题目分数
                    String scoresSql = "SELECT scores FROM exam_question WHERE exam_id = " + examId;
                    List<Map<String,Object>> scoresData = dataMapper.ssql(scoresSql);
                    String[] scores = new String[0];
                    if(scoresData.size() > 0 && scoresData.get(0).get("scores") != null) {
                        scores = scoresData.get(0).get("scores").toString().split(",");
                    }
                    
                    // 处理每道题目
                    for(int i = 0; i < allIds.length; i++) {
                        String qid = allIds[i];
                        Question question = questionService.getById(qid);
                        
                        if(question != null) {
                            // 获取题目权重
                            String weights = question.getWeight();
                            String[] bankIds = question.getQuBankId().split(",");
                            String[] weightValues = weights != null ? weights.split(",") : new String[bankIds.length];
                            
                            // 如果没有设置权重，默认为1
                            if(weights == null || weights.isEmpty()) {
                                for(int w = 0; w < weightValues.length; w++) {
                                    weightValues[w] = "1";
                                }
                            }
                            
                            // 获取题目分数
                            double score = 0;
                            if(i < scores.length) {
                                score = Double.parseDouble(scores[i]);
                            }
                            
                            // 判断是否做对了此题
                            boolean isCorrect = false;
                            for(String correctId : correctIds) {
                                if(correctId.equals(qid)) {
                                    isCorrect = true;
                                    break;
                                }
                            }
                            
                            // 根据是否做对计算分数
                            double questionScore = isCorrect ? score : 0;
                            
                            // 根据权重分配分数到各分类
                            for(int j = 0; j < bankIds.length; j++) {
                                Integer bankId = Integer.parseInt(bankIds[j]);
                                double weight = j < weightValues.length ? Double.parseDouble(weightValues[j]) : 1.0;
                                double weightedScore = questionScore * weight;
                                
                                weightedScoreMap.put(bankId, weightedScoreMap.getOrDefault(bankId, 0.0) + weightedScore);
                            }
                        }
                    }
                }
            }
        }
        
        // 构建返回结果
        for (QuestionBank questionBank : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", questionBank.getBankName());
            double value = weightedScoreMap.getOrDefault(questionBank.getBankId(), 0.0);
            map.put("value", value);
            mapList.add(map);
        }
        
        return CommonResult.<List>builder()
                .data(mapList)
                .build();
    }

}
